//张译文、曾凡诚
#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include "Component/dieselgen.h"
#include "Component/pv.h"
#include "Component/energystorage.h"
#include "Component/load.h"
#include "Component/grid.h"
#include "Component/gprice.h"  
#include "Schedule/Scheduler.h"
#include "Code/Simulator.h"
#include "ParamConfigDlg.h"
#include "ComponentPowerCurveDialog.h" 
#include <QMenu>
#include <QAction>
#include <QDialog>
#include <QPushButton>
#include <QLineEdit>
#include <QFileDialog>
#include <QMessageBox>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    dataMgr = new DataManager(this);
    simulator = new Simulator(this);
//张译文:实现鼠标右键生成菜单列表
//曾凡诚:补充了菜单列表
    // ---------- 组件右键菜单信号连接 ----------
    ui->DieselGen->setContextMenuPolicy(Qt::ContextMenuPolicy::CustomContextMenu);
    connect(ui->DieselGen, &QWidget::customContextMenuRequested, this, &MainWindow::on_DieselGen_customContextMenuRequested);
    ui->PV->setContextMenuPolicy(Qt::ContextMenuPolicy::CustomContextMenu);
    connect(ui->PV, &QWidget::customContextMenuRequested, this, &MainWindow::on_PV_customContextMenuRequested);
    ui->EnergyStorage->setContextMenuPolicy(Qt::ContextMenuPolicy::CustomContextMenu);
    connect(ui->EnergyStorage, &QWidget::customContextMenuRequested, this, &MainWindow::on_EnergyStorage_customContextMenuRequested);
    ui->Load->setContextMenuPolicy(Qt::ContextMenuPolicy::CustomContextMenu);
    connect(ui->Load, &QWidget::customContextMenuRequested, this, &MainWindow::on_Load_customContextMenuRequested);
    ui->Grid->setContextMenuPolicy(Qt::ContextMenuPolicy::CustomContextMenu);
    connect(ui->Grid, &QWidget::customContextMenuRequested, this, &MainWindow::on_Grid_customContextMenuRequested);
    ui->GPrice->setContextMenuPolicy(Qt::ContextMenuPolicy::CustomContextMenu);  
    connect(ui->GPrice, &QWidget::customContextMenuRequested, this, &MainWindow::on_GPrice_customContextMenuRequested);  

    ui->time->setText(QString("当前时间：%1").arg(simulator->getCurrentTime()));

    connect(ui->InitSystem, &QPushButton::clicked, this, &MainWindow::on_InitSystem_clicked);
//曾凡诚
    // ---------- DataManager与Simulator的信号连接 ----------
    connect(dataMgr, &DataManager::dieselGenTimePowerLoaded,
            simulator, &Simulator::onDieselGenTimePowerLoaded);
    connect(dataMgr, &DataManager::importFailed,
            this, [=](const QString& reason) {
                qDebug() << "柴油发电机CSV导入失败：importDGcsvfailed" << reason;
            });
    connect(dataMgr, &DataManager::pvDataLoaded,
            simulator, &Simulator::onPvDataLoaded);
    connect(dataMgr, &DataManager::energyStorageDataLoaded,
            simulator, &Simulator::onEnergyStorageDataLoaded);
    connect(dataMgr, &DataManager::loadDataLoaded,
            simulator, &Simulator::onLoadDataLoaded);
    connect(dataMgr, &DataManager::gridDataLoaded,
            simulator, &Simulator::onGridDataLoaded);
    connect(dataMgr, &DataManager::gPriceDataLoaded,  // 新增：电价数据加载信号
            simulator, &Simulator::onGPriceDataLoaded);
}

MainWindow::~MainWindow()
{
    delete ui;
}

// ---------- 电价组件“点击导入CSV”逻辑 ----------
void MainWindow::on_GPrice_clicked()
{
    importComponentData("选择电价CSV文件", &DataManager::importGPriceCsv);
}

// ---------- 电价组件右键菜单逻辑 ----------
void MainWindow::on_GPrice_customContextMenuRequested(const QPoint &pos)
{
    QMenu menu(this);
    // “导入数据”菜单项：点击后调用on_GPrice_clicked
    QAction *importAction = menu.addAction("导入数据");
    connect(importAction, &QAction::triggered, this, &MainWindow::on_GPrice_clicked, Qt::UniqueConnection);

    QAction *propAction = menu.addAction("属性");
    connect(propAction, &QAction::triggered, this, &MainWindow::onGPricePropClicked, Qt::UniqueConnection);

    QAction *exportAction = menu.addAction("导出数据");
    connect(exportAction, &QAction::triggered, this, &MainWindow::onGPriceExportClicked, Qt::UniqueConnection);


    // “绘制功率曲线”选项
    QAction *drawCurveAction = menu.addAction("绘制功率曲线");
    connect(drawCurveAction, &QAction::triggered, this, &MainWindow::onDrawGPricePowerCurve, Qt::UniqueConnection);


    menu.exec(ui->GPrice->mapToGlobal(pos));
}

// ---------- 电价属性对话框逻辑 ----------
void MainWindow::onGPricePropClicked()
{
    disconnect(ui->GPrice, &QWidget::customContextMenuRequested, this, &MainWindow::on_GPrice_customContextMenuRequested);

    double currentPrice = 0.0;
    // 从simulator中查找“电价组件”的当前值（约定ID为6，与其他组件不重复）
    for (const auto& param : simulator->currentState.componentParams) {
        if (param.id == 6) {
            currentPrice = param.currentPower;  // 复用currentPower字段存储电价数值
            break;
        }
    }

    GPrice dialog(this);
    QLineEdit *priceEdit = dialog.findChild<QLineEdit*>("priceEdit");
    if (priceEdit != nullptr) {
        priceEdit->setText(QString::number(currentPrice, 'f', 2));
    } else {
        qDebug() << "错误：电价对话框未找到 priceEdit 控件！";
    }

    // 连接对话框的paramsUpdated信号，同步“当前状态”和“时间-电价映射表”
    connect(&dialog, &GPrice::paramsUpdated, this, [this](const ComponentParam& param) {
        for (auto& compParam : simulator->currentState.componentParams) {
            if (compParam.id == 6) {
                compParam.currentPower = param.currentPower;  // 复用currentPower存储电价
                break;
            }
        }
        int currentTime = simulator->getCurrentTime();
        simulator->gPriceTimePriceMap[currentTime] = param.currentPower;  // 电价专属的时间-数值映射表
        qDebug() << "电价：当前状态和映射表（时间" << currentTime << "）已同步，电价=" << param.currentPower;
    });

    dialog.exec();
    connect(ui->GPrice, &QWidget::customContextMenuRequested, this, &MainWindow::on_GPrice_customContextMenuRequested);
}

// ---------- 电价参数更新槽函数 ----------
void MainWindow::GPriceParamsUpdated(ComponentParam editparam) {
    for (auto& param : simulator->currentState.componentParams) {
        if (param.id == 6) {
            param.currentPower = editparam.currentPower;
            break;
        }
    }
    qDebug() << "电价已更新：" << editparam.currentPower;
}

// ---------- 电价数据导出逻辑 ----------
void MainWindow::onGPriceExportClicked()
{
    QString savePath = QFileDialog::getSaveFileName(
        this, "导出电价数据", ".", "CSV文件 (*.csv);;所有文件 (*.*)");
    if (savePath.isEmpty()) {
        return;
    }

    QMap<int, float> gPriceData = simulator->gPriceTimePriceMap;

    connect(dataMgr, &DataManager::exportFailed, this, [=](const QString& reason) {
        QMessageBox::warning(this, "导出失败", reason);
        disconnect(dataMgr, &DataManager::exportFailed, this, nullptr);
    }, Qt::UniqueConnection);

    dataMgr->exportGPriceCsv(savePath, gPriceData);
}

// --------------------
void MainWindow::importComponentData(const QString& dialogTitle,
                                     void (DataManager::*importFunc)(const QString&))
{
    QString filePath = QFileDialog::getOpenFileName(
        this, dialogTitle, ".", "CSV文件 (*.csv)");
    if (!filePath.isEmpty()) {
        (dataMgr->*importFunc)(filePath);
        qDebug() << dialogTitle << "导入路径：" << filePath;
    }
}

void MainWindow::on_DieselGen_clicked()
{
    importComponentData("选择柴油发电机CSV文件", &DataManager::importDieselGenCsv);
}

void MainWindow::on_PV_clicked()
{
    importComponentData("选择光伏CSV文件", &DataManager::importPvCsv);
}

void MainWindow::on_EnergyStorage_clicked()
{
    importComponentData("选择储能CSV文件", &DataManager::importEnergyStorageCsv);
}

void MainWindow::on_Load_clicked()
{
    importComponentData("选择负载CSV文件", &DataManager::importLoadCsv);
}

void MainWindow::on_Grid_clicked()
{
    importComponentData("选择电网CSV文件", &DataManager::importGridCsv);
}

void MainWindow::on_DieselGen_customContextMenuRequested(const QPoint &pos)
{
    QMenu menu(this);
    QAction *importAction = menu.addAction("导入数据");
    connect(importAction, &QAction::triggered, this, &MainWindow::on_DieselGen_clicked, Qt::UniqueConnection);

    QAction *propAction = menu.addAction("属性");
    connect(propAction, &QAction::triggered, this, &MainWindow::onDieselGenPropClicked, Qt::UniqueConnection);

    QAction *exportAction = menu.addAction("导出数据");
    connect(exportAction, &QAction::triggered, this, &MainWindow::onDieselGenExportClicked, Qt::UniqueConnection);

    
    QAction *drawCurveAction = menu.addAction("绘制功率曲线");
    connect(drawCurveAction, &QAction::triggered, this, &MainWindow::onDrawDieselGenPowerCurve, Qt::UniqueConnection);


    menu.exec(ui->DieselGen->mapToGlobal(pos));
}

void MainWindow::on_PV_customContextMenuRequested(const QPoint &pos)
{
    QMenu menu(this);
    QAction *importAction = menu.addAction("导入数据");
    connect(importAction, &QAction::triggered, this, &MainWindow::on_PV_clicked, Qt::UniqueConnection);

    QAction *propAction = menu.addAction("属性");
    connect(propAction, &QAction::triggered, this, &MainWindow::onPVPropClicked, Qt::UniqueConnection);

    QAction *exportAction = menu.addAction("导出数据");
    connect(exportAction, &QAction::triggered, this, &MainWindow::onPVExportClicked, Qt::UniqueConnection);

    
    QAction *drawCurveAction = menu.addAction("绘制功率曲线");
    connect(drawCurveAction, &QAction::triggered, this, &MainWindow::onDrawPVPowerCurve, Qt::UniqueConnection);


    menu.exec(ui->PV->mapToGlobal(pos));
}

void MainWindow::on_EnergyStorage_customContextMenuRequested(const QPoint &pos)
{
    QMenu menu(this);
    QAction *importAction = menu.addAction("导入数据");
    connect(importAction, &QAction::triggered, this, &MainWindow::on_EnergyStorage_clicked, Qt::UniqueConnection);

    QAction *propAction = menu.addAction("属性");
    connect(propAction, &QAction::triggered, this, &MainWindow::onEnergyStoragePropClicked, Qt::UniqueConnection);

    QAction *exportAction = menu.addAction("导出数据");
    connect(exportAction, &QAction::triggered, this, &MainWindow::onEnergyStorageExportClicked, Qt::UniqueConnection);

    
    QAction *drawCurveAction = menu.addAction("绘制功率曲线");
    connect(drawCurveAction, &QAction::triggered, this, &MainWindow::onDrawEnergyStoragePowerCurve, Qt::UniqueConnection);


    menu.exec(ui->EnergyStorage->mapToGlobal(pos));
}

void MainWindow::on_Load_customContextMenuRequested(const QPoint &pos)
{
    QMenu menu(this);
    QAction *importAction = menu.addAction("导入数据");
    connect(importAction, &QAction::triggered, this, &MainWindow::on_Load_clicked, Qt::UniqueConnection);

    QAction *propAction = menu.addAction("属性");
    connect(propAction, &QAction::triggered, this, &MainWindow::onLoadPropClicked, Qt::UniqueConnection);

    QAction *exportAction = menu.addAction("导出数据");
    connect(exportAction, &QAction::triggered, this, &MainWindow::onLoadExportClicked, Qt::UniqueConnection);

    
    QAction *drawCurveAction = menu.addAction("绘制功率曲线");
    connect(drawCurveAction, &QAction::triggered, this, &MainWindow::onDrawLoadPowerCurve, Qt::UniqueConnection);
    menu.exec(ui->Load->mapToGlobal(pos));
}

void MainWindow::on_Grid_customContextMenuRequested(const QPoint &pos)
{
    QMenu menu(this);
    QAction *importAction = menu.addAction("导入数据");
    connect(importAction, &QAction::triggered, this, &MainWindow::on_Grid_clicked, Qt::UniqueConnection);

    QAction *propAction = menu.addAction("属性");
    connect(propAction, &QAction::triggered, this, &MainWindow::onGridPropClicked, Qt::UniqueConnection);

    QAction *exportAction = menu.addAction("导出数据");
    connect(exportAction, &QAction::triggered, this, &MainWindow::onGridExportClicked, Qt::UniqueConnection);

    QAction *drawCurveAction = menu.addAction("绘制功率曲线");
    connect(drawCurveAction, &QAction::triggered, this, &MainWindow::onDrawGridPowerCurve, Qt::UniqueConnection);

    menu.exec(ui->Grid->mapToGlobal(pos));
}

void MainWindow::onDieselGenPropClicked()
{   qDebug() <<"chufa__power__";
    disconnect(ui->DieselGen, &QWidget::customContextMenuRequested, this, &MainWindow::on_DieselGen_customContextMenuRequested);
    qDebug() << "componentParams大小：" << simulator->currentState.componentParams.size(); // 新增
    double currentPower = 0.0;
    for (const auto& param : simulator->currentState.componentParams) {
        if (param.id == 3) {
            currentPower = param.currentPower;
            qDebug() <<"dangqian__power__"<<currentPower;
            break;
        }
        else
            qDebug()<<"my___";
    }

    DieselGen dialog(this);
    QLineEdit *powerEdit = dialog.findChild<QLineEdit*>("powerEdit");
    if (powerEdit != nullptr) {
        powerEdit->setText(QString::number(currentPower, 'f', 2));
    } else {
        qDebug() << "错误：柴油发电机对话框未找到 powerEdit 控件！";
    }

    connect(&dialog, &DieselGen::paramsUpdated, this, [this](const ComponentParam& param) {
        for (auto& compParam : simulator->currentState.componentParams) {
            if (compParam.id == 3) {
                compParam.currentPower = param.currentPower;
                break;
            }
        }
        int currentTime = simulator->getCurrentTime();
        simulator->dieselGenTimePowerMap[currentTime] = param.currentPower;
        qDebug() << "柴油发电机：当前状态和映射表（时间" << currentTime << "）已同步，功率=" << param.currentPower;
    });

    dialog.exec();
    connect(ui->DieselGen, &QWidget::customContextMenuRequested, this, &MainWindow::on_DieselGen_customContextMenuRequested);
}

void MainWindow::onPVPropClicked()
{
    disconnect(ui->PV, &QWidget::customContextMenuRequested, this, &MainWindow::on_PV_customContextMenuRequested);

    double currentPower = 0.0;
    for (const auto& param : simulator->currentState.componentParams) {
        if (param.id == 1) {
            currentPower = param.currentPower;
            break;
        }
    }

    PV dialog(this);
    QLineEdit *powerEdit = dialog.findChild<QLineEdit*>("powerEdit");
    if (powerEdit != nullptr) {
        powerEdit->setText(QString::number(currentPower, 'f', 2));
    } else {
        qDebug() << "错误：光伏对话框未找到 powerEdit 控件！";
    }

    connect(&dialog, &PV::paramsUpdated, this, [this](const ComponentParam& param) {
        for (auto& compParam : simulator->currentState.componentParams) {
            if (compParam.id == 1) {
                compParam.currentPower = param.currentPower;
                break;
            }
        }
        int currentTime = simulator->getCurrentTime();
        simulator->pvTimePowerMap[currentTime] = param.currentPower;
        qDebug() << "光伏：当前状态和映射表（时间" << currentTime << "）已同步，功率=" << param.currentPower;
    });

    dialog.exec();
    connect(ui->PV, &QWidget::customContextMenuRequested, this, &MainWindow::on_PV_customContextMenuRequested);
}

void MainWindow::onEnergyStoragePropClicked()
{
    disconnect(ui->EnergyStorage, &QWidget::customContextMenuRequested, this, &MainWindow::on_EnergyStorage_customContextMenuRequested);

    double currentPower = 0.0;
    for (const auto& param : simulator->currentState.componentParams) {
        if (param.id == 2) {
            currentPower = param.currentPower;
            break;
        }
    }

    EnergyStorage dialog(this);
    QLineEdit *powerEdit = dialog.findChild<QLineEdit*>("powerEdit");
    if (powerEdit != nullptr) {
        powerEdit->setText(QString::number(currentPower, 'f', 2));
    } else {
        qDebug() << "错误：储能对话框未找到 powerEdit 控件！";
    }

    connect(&dialog, &EnergyStorage::paramsUpdated, this, [this](const ComponentParam& param) {
        for (auto& compParam : simulator->currentState.componentParams) {
            if (compParam.id == 2) {
                compParam.currentPower = param.currentPower;
                break;
            }
        }
        int currentTime = simulator->getCurrentTime();
        simulator->energyStorageTimePowerMap[currentTime] = param.currentPower;
        qDebug() << "储能：当前状态和映射表（时间" << currentTime << "）已同步，功率=" << param.currentPower;
    });

    dialog.exec();
    connect(ui->EnergyStorage, &QWidget::customContextMenuRequested, this, &MainWindow::on_EnergyStorage_customContextMenuRequested);
}

void MainWindow::onLoadPropClicked()
{
    disconnect(ui->Load, &QWidget::customContextMenuRequested, this, &MainWindow::on_Load_customContextMenuRequested);

    double currentPower = 0.0;
    for (const auto& param : simulator->currentState.componentParams) {
        if (param.id == 4) {
            currentPower = param.currentPower;
            break;
        }
    }

    Load dialog(this);
    QLineEdit *powerEdit = dialog.findChild<QLineEdit*>("powerEdit");
    if (powerEdit != nullptr) {
        powerEdit->setText(QString::number(currentPower, 'f', 2));
    } else {
        qDebug() << "错误：负载对话框未找到 powerEdit 控件！";
    }

    connect(&dialog, &Load::paramsUpdated, this, [this](const ComponentParam& param) {
        for (auto& compParam : simulator->currentState.componentParams) {
            if (compParam.id == 4) {
                compParam.currentPower = param.currentPower;
                break;
            }
        }
        int currentTime = simulator->getCurrentTime();
        simulator->loadTimePowerMap[currentTime] = param.currentPower;
        qDebug() << "负载：当前状态和映射表（时间" << currentTime << "）已同步，功率=" << param.currentPower;
    });

    dialog.exec();
    connect(ui->Load, &QWidget::customContextMenuRequested, this, &MainWindow::on_Load_customContextMenuRequested);
}

void MainWindow::onGridPropClicked()
{
    disconnect(ui->Grid, &QWidget::customContextMenuRequested, this, &MainWindow::on_Grid_customContextMenuRequested);

    double currentPower = 0.0;
    for (const auto& param : simulator->currentState.componentParams) {
        if (param.id == 5) {
            currentPower = param.currentPower;
            break;
        }
    }

    Grid dialog(this);
    QLineEdit *powerEdit = dialog.findChild<QLineEdit*>("powerEdit");
    if (powerEdit != nullptr) {
        powerEdit->setText(QString::number(currentPower, 'f', 2));
    } else {
        qDebug() << "错误：电网对话框未找到 powerEdit 控件！";
    }

    connect(&dialog, &Grid::paramsUpdated, this, [this](const ComponentParam& param) {
        for (auto& compParam : simulator->currentState.componentParams) {
            if (compParam.id == 5) {
                compParam.currentPower = param.currentPower;
                break;
            }
        }
        int currentTime = simulator->getCurrentTime();
        simulator->gridTimePowerMap[currentTime] = param.currentPower;
        qDebug() << "电网：当前状态和映射表（时间" << currentTime << "）已同步，功率=" << param.currentPower;
    });

    dialog.exec();
    connect(ui->Grid, &QWidget::customContextMenuRequested, this, &MainWindow::on_Grid_customContextMenuRequested);
}

void MainWindow::on_TimeUpdate_clicked()
{
    ui->time->setText(QString("当前时间：%1").arg(simulator->getCurrentTime()));
}

void MainWindow::on_InitSystem_clicked()
{
    simulator->initializeSystem();
    qDebug() << "InitSystem";
}

void MainWindow::DieselGenParamsUpdated(ComponentParam editparam) {
    for (auto& param : simulator->currentState.componentParams) {
        if (param.id == 3) {
            param.currentPower = editparam.currentPower;
            break;
        }
    }
    qDebug() << "update" << editparam.currentPower;
}

void MainWindow::PVParamsUpdated(ComponentParam editparam) {
    for (auto& param : simulator->currentState.componentParams) {
        if (param.id == 1) {
            param.currentPower = editparam.currentPower;
            break;
        }
    }
    qDebug() << "光伏功率已更新：" << editparam.currentPower;
}

void MainWindow::EnergyStorageParamsUpdated(ComponentParam editparam) {
    for (auto& param : simulator->currentState.componentParams) {
        if (param.id == 2) {
            param.currentPower = editparam.currentPower;
            break;
        }
    }
    qDebug() << "储能功率已更新：" << editparam.currentPower;
}

void MainWindow::LoadParamsUpdated(ComponentParam editparam) {
    for (auto& param : simulator->currentState.componentParams) {
        if (param.id == 4) {
            param.currentPower = editparam.currentPower;
            break;
        }
    }
    qDebug() << "负载功率已更新：" << editparam.currentPower;
}

void MainWindow::GridParamsUpdated(ComponentParam editparam) {
    for (auto& param : simulator->currentState.componentParams) {
        if (param.id == 5) {
            param.currentPower = editparam.currentPower;
            break;
        }
    }
    qDebug() << "电网功率已更新：" << editparam.currentPower;
}

void MainWindow::onDieselGenExportClicked()
{
    QString savePath = QFileDialog::getSaveFileName(
        this, "导出柴油发电机数据", ".", "CSV文件 (*.csv);;所有文件 (*.*)");
    if (savePath.isEmpty()) {
        return;
    }

    QMap<int, float> dieselData = simulator->dieselGenTimePowerMap;

    connect(dataMgr, &DataManager::exportFailed, this, [=](const QString& reason) {
        QMessageBox::warning(this, "导出失败", reason);
        disconnect(dataMgr, &DataManager::exportFailed, this, nullptr);
    }, Qt::UniqueConnection);

    dataMgr->exportDieselGenCsv(savePath, dieselData);
}

void MainWindow::onPVExportClicked()
{
    QString savePath = QFileDialog::getSaveFileName(
        this, "导出光伏数据", ".", "CSV文件 (*.csv);;所有文件 (*.*)");
    if (savePath.isEmpty()) {
        return;
    }

    QMap<int, float> pvData = simulator->pvTimePowerMap;

    connect(dataMgr, &DataManager::exportFailed, this, [=](const QString& reason) {
        QMessageBox::warning(this, "导出失败", reason);
        disconnect(dataMgr, &DataManager::exportFailed, this, nullptr);
    }, Qt::UniqueConnection);

    dataMgr->exportPvCsv(savePath, pvData);
}

void MainWindow::onEnergyStorageExportClicked()
{
    QString savePath = QFileDialog::getSaveFileName(
        this, "导出储能数据", ".", "CSV文件 (*.csv);;所有文件 (*.*)");
    if (savePath.isEmpty()) {
        return;
    }

    QMap<int, float> esData = simulator->energyStorageTimePowerMap;

    connect(dataMgr, &DataManager::exportFailed, this, [=](const QString& reason) {
        QMessageBox::warning(this, "导出失败", reason);
        disconnect(dataMgr, &DataManager::exportFailed, this, nullptr);
    }, Qt::UniqueConnection);

    dataMgr->exportEnergyStorageCsv(savePath, esData);
}

void MainWindow::onLoadExportClicked()
{
    QString savePath = QFileDialog::getSaveFileName(
        this, "导出负载数据", ".", "CSV文件 (*.csv);;所有文件 (*.*)");
    if (savePath.isEmpty()) {
        return;
    }

    QMap<int, float> loadData = simulator->loadTimePowerMap;

    connect(dataMgr, &DataManager::exportFailed, this, [=](const QString& reason) {
        QMessageBox::warning(this, "导出失败", reason);
        disconnect(dataMgr, &DataManager::exportFailed, this, nullptr);
    }, Qt::UniqueConnection);

    dataMgr->exportLoadCsv(savePath, loadData);
}

void MainWindow::onGridExportClicked()
{
    QString savePath = QFileDialog::getSaveFileName(
        this, "导出电网数据", ".", "CSV文件 (*.csv);;所有文件 (*.*)");
    if (savePath.isEmpty()) {
        return;
    }

    QMap<int, float> gridData = simulator->gridTimePowerMap;

    connect(dataMgr, &DataManager::exportFailed, this, [=](const QString& reason) {
        QMessageBox::warning(this, "导出失败", reason);
        disconnect(dataMgr, &DataManager::exportFailed, this, nullptr);
    });

    dataMgr->exportGridCsv(savePath, gridData);
}

void MainWindow::on_pushButton_2_clicked()
{
    simulator->backTimeStep();
    qDebug() << simulator->getCurrentTime();
    ui->time->setText(QString("当前时间：%1").arg(simulator->getCurrentTime()));
}

void MainWindow::on_pushButton_clicked()
{
    simulator->advanceTimeStep();
    qDebug() << simulator->getCurrentTime();
    ui->time->setText(QString("当前时间：%1").arg(simulator->getCurrentTime()));
}

void MainWindow::on_btnEconomicDispatch_clicked()
{
    if (simulator && simulator->getScheduler()) {
        simulator->getScheduler()->setAlgorithmType("经济调度");
        qDebug() << "已切换为【经济调度】算法";
    }
}


void MainWindow::on_btnRuleBasedDispatch_clicked()
{
    if (simulator && simulator->getScheduler()) {
        simulator->getScheduler()->setAlgorithmType("规则调度");
        qDebug() << "已切换为【规则调度】算法";
    }
}


void MainWindow::on_btnStartSimulation_clicked()
{
    // 1. 检查仿真器和调度器是否有效（避免空指针崩溃）
    if (!simulator || !simulator->getScheduler()) {
        QMessageBox::warning(this, "启动失败", "仿真器或调度器未初始化！");
        return;
    }

    // 2. 检查系统是否已初始化（componentParams 非空，避免调度时无数据）
    if (simulator->currentState.componentParams.isEmpty()) {
        QMessageBox::information(this, "提示", "请先点击「初始化系统」按钮，再启动仿真！");
        return;
    }

    // 3. 检查是否已选择调度算法（经济/规则调度，避免用默认算法导致结果不符合预期）
    QString algoType = QString::fromStdString(simulator->getScheduler()->algorithmType);
    if (algoType.isEmpty()) {
        QMessageBox::information(this, "提示", "请先选择method__调度算法（经济调度/规则调度），再启动仿真！");
        return;
    }

    // 4. 调用 startSimulation() 启动仿真（内部会循环推进时间步 + 触发调度）
    // 注：参数 stepSec 是“每步的秒数”，按你的设计填（比如1小时=3600秒）
    int stepSec = 3600;
    qDebug() << "开始仿真，每步时长：" << stepSec << "秒，调度算法：" << algoType;
    simulator->startSimulation(stepSec);

}


void MainWindow::on_btnConfigParam_clicked()
{
    // 1. 检查Simulator是否初始化
    if (!simulator) {
        QMessageBox::warning(this, "错误", "Simulator还没初始化！");
        return;
    }

    // 2. 打开参数配置弹窗
    ParamConfigDlg dlg(this);
    // 3. 回显当前参数（从Simulator读值）
    dlg.setInitParams(
        simulator->getDieselGenMaxPower(),
        simulator->getDieselGenMinPower(),
        simulator->getDieselCostPerKwh(),
        simulator->getEnergyStorageCapacity()
        );

    // 4. 接收弹窗传来的新参数，更新到Simulator
    connect(&dlg, &ParamConfigDlg::paramsSaved, this, [this](float dieselMax, float dieselMin, float dieselCost, float essCap) {
        simulator->setDieselGenMaxPower(dieselMax);
        simulator->setDieselGenMinPower(dieselMin);
        simulator->setDieselCostPerKwh(dieselCost);
        simulator->setEnergyStorageCapacity(essCap);
        QMessageBox::information(this, "成功", "参数已更新！");
    });

    // 5. 显示弹窗（阻塞式，直到用户操作）
    dlg.exec();
}

void MainWindow::onDrawDieselGenPowerCurve()
{
    ComponentPowerCurveDialog *dlg = new ComponentPowerCurveDialog(this);
    // 传入柴油发电机的“时间-功率”映射表 + 组件名称
    dlg->setComponentData(simulator->dieselGenTimePowerMap, "柴油发电机");
    dlg->exec(); // 显示对话框（阻塞式，直到关闭）
}

void MainWindow::onDrawPVPowerCurve()
{
    ComponentPowerCurveDialog *dlg = new ComponentPowerCurveDialog(this);
    dlg->setComponentData(simulator->pvTimePowerMap, "光伏");
    dlg->exec();
}

void MainWindow::onDrawEnergyStoragePowerCurve()
{
    ComponentPowerCurveDialog *dlg = new ComponentPowerCurveDialog(this);
    dlg->setComponentData(simulator->energyStorageTimePowerMap, "储能");
    dlg->exec();
}

void MainWindow::onDrawLoadPowerCurve()
{
    ComponentPowerCurveDialog *dlg = new ComponentPowerCurveDialog(this);
    dlg->setComponentData(simulator->loadTimePowerMap, "负载");
    dlg->exec();
}

void MainWindow::onDrawGridPowerCurve()
{
    ComponentPowerCurveDialog *dlg = new ComponentPowerCurveDialog(this);
    dlg->setComponentData(simulator->gridTimePowerMap, "电网");
    dlg->exec();
}

void MainWindow::onDrawGPricePowerCurve()
{
    ComponentPowerCurveDialog *dlg = new ComponentPowerCurveDialog(this);
    // 传入电价的“时间-价格”映射表 + 组件名称
    dlg->setComponentData(simulator->gPriceTimePriceMap, "电价");
    dlg->exec();
}
